<template>
  <div class="student-management">
    <div class="page-header">
      <div class="header-left">
        <button class="back-btn" @click="goBack">返回主页</button>
        <h2>学生管理</h2>
      </div>
      <button class="add-btn" @click="showAddModal = true">新增学生</button>
    </div>
    
    <div class="filter-bar">
      <div class="filter-group">
        <label>班级：</label>
        <select v-model="filters.class_id" @change="handleClassChange">
          <option value="">全部班级</option>
          <option v-for="cls in classes" :key="cls.id" :value="cls.id">
            {{ cls.className }}
          </option>
        </select>
      </div>
      <div class="filter-group">
        <input 
          type="text" 
          v-model="filters.search" 
          placeholder="搜索学生姓名或学号"
          @keyup.enter="handleSearch"
        >
        <button class="search-btn" @click="handleSearch">搜索</button>
      </div>
      <div class="filter-group">
        <label>每页条数：</label>
        <select v-model="pagination.pageSize" @change="handlePageSizeChange">
          <option v-for="size in pagination.pageSizes" :key="size" :value="size">
            {{ size }}
          </option>
        </select>
      </div>
    </div>
    
    <div class="student-list">
      <table class="student-table">
        <thead>
          <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>班级</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="student in students" :key="student.id">
            <td>{{ student.username }}</td>
            <td>{{ student.name }}</td>
            <td>{{ student.class_name || '未分配班级' }}</td>
            <td>{{ formatDate(student.createdAt) }}</td>
            <td>
              <button class="edit-btn" @click="editStudent(student)">编辑</button>
              <button class="delete-btn" @click="deleteStudent(student.id)">删除</button>
              <button class="reset-btn" @click="resetPassword(student.id)">重置密码</button>
            </td>
          </tr>
        </tbody>
      </table>
      <div v-if="students.length === 0" class="empty-tip">暂无学生数据</div>
      
      <!-- 分页组件 -->
      <div class="pagination" v-if="pagination.total > 0">
        <div class="pagination-info">
          共 {{ pagination.total }} 条记录，第 {{ pagination.currentPage }} / {{ Math.ceil(pagination.total / pagination.pageSize) }} 页
        </div>
        <div class="pagination-controls">
          <button 
            class="page-btn" 
            :disabled="pagination.currentPage === 1"
            @click="goToPage(1)"
          >
            首页
          </button>
          <button 
            class="page-btn" 
            :disabled="pagination.currentPage === 1"
            @click="goToPage(pagination.currentPage - 1)"
          >
            上一页
          </button>
          <button 
            class="page-btn" 
            :disabled="pagination.currentPage === Math.ceil(pagination.total / pagination.pageSize)"
            @click="goToPage(pagination.currentPage + 1)"
          >
            下一页
          </button>
          <button 
            class="page-btn" 
            :disabled="pagination.currentPage === Math.ceil(pagination.total / pagination.pageSize)"
            @click="goToPage(Math.ceil(pagination.total / pagination.pageSize))"
          >
            末页
          </button>
          <div class="page-jump">
            <input 
              type="number" 
              v-model="jumpPage" 
              min="1" 
              :max="Math.ceil(pagination.total / pagination.pageSize)"
              @keyup.enter="handleJump"
            >
            <button class="jump-btn" @click="handleJump">跳转</button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 新增/编辑学生弹窗 -->
    <div class="modal" v-if="showAddModal || showEditModal" @click="closeModal">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>{{ isEditMode ? '编辑学生' : '新增学生' }}</h3>
          <button class="close-btn" @click="closeModal">×</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveStudent">
            <div class="form-group">
              <label>学号 *</label>
              <input 
                type="text" 
                v-model="studentForm.username" 
                :disabled="isEditMode" 
                required 
                placeholder="请输入学号"
              >
            </div>
            <div class="form-group">
              <label>姓名 *</label>
              <input type="text" v-model="studentForm.name" required placeholder="请输入姓名">
            </div>
            <div class="form-group" v-if="!isEditMode">
              <label>初始密码 *</label>
              <input type="password" v-model="studentForm.password" required placeholder="请输入初始密码">
            </div>
            <div class="form-group">
              <label>班级</label>
              <select v-model="studentForm.class_id">
                <option value="">未分配班级</option>
                <option v-for="cls in classes" :key="cls.id" :value="cls.id">
                  {{ cls.className }}
                </option>
              </select>
            </div>
            <div class="modal-footer">
              <button type="submit" class="submit-btn">{{ isEditMode ? '保存' : '创建' }}</button>
              <button type="button" class="cancel-btn" @click="closeModal">取消</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { api } from '@/utils/api.js';
import { showMessage } from '@/utils/common.js';
import { formatDate } from '@/utils/common.js';

export default {
  name: 'StudentManagement',
  data() {
    return {
      students: [],
      classes: [],
      filters: {
        class_id: '',
        search: ''
      },
      showAddModal: false,
      showEditModal: false,
      isEditMode: false,
      studentForm: {
        id: '',
        username: '',
        name: '',
        password: '',
        class_id: ''
      },
      // 分页相关状态
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
        pageSizes: [10, 20, 50, 100]
      },
      // 跳转页码输入值
      jumpPage: 1
    };
  },
  methods: {
    // 格式化日期时间
    formatDate,
    
    /**
     * 返回教师主页
     */
    goBack() {
      this.$router.push('/teacher/home');
    },
    
    /**
     * 初始化数据
     */
    async initData() {
      await this.loadClasses();
      await this.loadStudents();
    },
    
    /**
     * 加载班级列表
     */
    async loadClasses() {
      try {
        const response = await api.getClasses();
        // 从response.data.classes中获取班级数据，适配后端返回格式
        this.classes = response.data?.classes || response.data || [];
      } catch (error) {
        showMessage(error.message || '加载班级列表失败', 'error');
      }
    },
    
    /**
     * 加载学生列表
     */
    async loadStudents() {
      try {
        this.loading = true;
        // 构建筛选条件
        const filters = {
          class_id: this.filters.class_id,
          search: this.filters.search
        };
        
        // 调用更新后的API方法，传递筛选条件、页码和每页数量
        const response = await api.getStudents(filters, this.pagination.currentPage, this.pagination.pageSize);
        
        // 处理后端返回的分页数据结构
        if (response.success && response.data) {
          this.students = response.data.students || [];
          this.pagination.total = response.data.total || 0;
        } else {
          // 适配可能的错误响应
          this.students = [];
          this.pagination.total = 0;
        }
      } catch (error) {
        showMessage(error.message || '加载学生列表失败', 'error');
        console.error('加载学生列表错误:', error);
      } finally {
        this.loading = false;
      }
    },
    
    /**
     * 处理班级筛选变化
     */
    handleClassChange() {
      this.pagination.currentPage = 1; // 重置到第一页
      this.loadStudents();
    },
    
    /**
     * 处理搜索
     */
    handleSearch() {
      this.pagination.currentPage = 1; // 重置到第一页
      this.loadStudents();
    },
    
    /**
     * 处理每页条数变化
     */
    handlePageSizeChange() {
      this.pagination.currentPage = 1; // 重置到第一页
      this.loadStudents();
    },
    
    /**
     * 跳转到指定页码
     */
    goToPage(page) {
      if (page >= 1 && page <= Math.ceil(this.pagination.total / this.pagination.pageSize)) {
        this.pagination.currentPage = page;
        this.loadStudents();
      }
    },
    
    /**
     * 处理页码输入跳转
     */
    handleJump() {
      const page = parseInt(this.jumpPage);
      if (!isNaN(page)) {
        this.goToPage(page);
      } else {
        this.jumpPage = this.pagination.currentPage;
      }
    },
    
    /**
     * 显示编辑学生弹窗
     */
    editStudent(student) {
      this.studentForm = {
        id: student.id,
        username: student.username,
        name: student.name,
        class_id: student.classId || ''
      };
      this.isEditMode = true;
      this.showEditModal = true;
      this.showAddModal = false;
    },
    
    /**
     * 关闭弹窗
     */
    closeModal() {
      this.showAddModal = false;
      this.showEditModal = false;
      this.resetForm();
    },
    
    /**
     * 重置表单
     */
    resetForm() {
      this.studentForm = {
        id: '',
        username: '',
        name: '',
        password: '',
        class_id: ''
      };
      this.isEditMode = false;
    },
    
    /**
     * 保存学生信息
     */
    async saveStudent() {
      try {
        const data = {
          name: this.studentForm.name,
          class_id: this.studentForm.class_id || null
        };
        
        if (!this.isEditMode) {
          data.username = this.studentForm.username;
          data.password = this.studentForm.password;
          data.role = 'student';
          await api.createUser(data);
          showMessage('学生创建成功', 'success');
        } else {
          await api.updateUser(this.studentForm.id, data);
          showMessage('学生信息更新成功', 'success');
        }
        
        this.closeModal();
        // 保存后可能总数变化，重新从第一页加载
        this.pagination.currentPage = 1;
        this.loadStudents();
      } catch (error) {
        showMessage(error.message || '操作失败', 'error');
      }
    },
    
    /**
     * 删除学生
     */
    async deleteStudent(studentId) {
      if (confirm('确定要删除该学生吗？删除后相关数据将无法恢复。')) {
        try {
          await api.deleteUser(studentId);
          showMessage('学生删除成功', 'success');
          
          // 检查当前页是否还有数据，如果没有则返回上一页
          const newTotal = this.pagination.total - 1;
          const totalPages = Math.ceil(newTotal / this.pagination.pageSize);
          if (this.pagination.currentPage > totalPages && totalPages > 0) {
            this.pagination.currentPage = totalPages;
          }
          
          this.loadStudents();
        } catch (error) {
          showMessage(error.message || '删除失败', 'error');
        }
      }
    },
    
    /**
     * 重置密码
     */
    async resetPassword(studentId) {
      if (confirm('确定要重置该学生的密码吗？重置后密码将变为默认密码123456。')) {
        try {
          await api.resetPassword(studentId);
          showMessage('密码重置成功，新密码为123456', 'success');
        } catch (error) {
          showMessage(error.message || '重置密码失败', 'error');
        }
      }
    }
  },
  mounted() {
    this.initData();
  }
};
</script>

<style scoped>
.student-management {
  padding: 20px;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e8e8e8;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.back-btn {
  padding: 6px 12px;
  background-color: #f0f0f0;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.back-btn:hover {
  background-color: #e0e0e0;
}

.add-btn,
.edit-btn,
.delete-btn,
.reset-btn,
.search-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s;
  margin-left: 5px;
}

.add-btn {
  background-color: #1E9FFF;
  color: white;
}

.add-btn:hover {
  background-color: #40A9FF;
}

.edit-btn {
  background-color: #52c41a;
  color: white;
}

.edit-btn:hover {
  background-color: #73d13d;
}

.delete-btn {
  background-color: #ff4d4f;
  color: white;
}

.delete-btn:hover {
  background-color: #ff7875;
}

.reset-btn {
  background-color: #faad14;
  color: white;
}

.reset-btn:hover {
  background-color: #ffc53d;
}

.search-btn {
  background-color: #1E9FFF;
  color: white;
}

.search-btn:hover {
  background-color: #40A9FF;
}

.filter-bar {
  background-color: #f5f5f5;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  gap: 20px;
  align-items: center;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-group label {
  color: #666;
  font-weight: 500;
}

.filter-group input,
.filter-group select {
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  min-width: 150px;
  color: #333;
}

.filter-group input {
  min-width: 200px;
}

.student-list {
  flex: 1;
  min-height: 0;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: auto;
}

.student-table {
  width: 100%;
  border-collapse: collapse;
}

.student-table th {
  background-color: #f5f5f5;
  padding: 12px;
  text-align: left;
  font-weight: 500;
  color: #666;
  border-bottom: 2px solid #e8e8e8;
}

.student-table td {
  padding: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.empty-tip {
      text-align: center;
      padding: 60px;
      color: #999;
    }
    
    /* 分页样式 */
    .pagination {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 20px;
      border-top: 1px solid #f0f0f0;
      background-color: #fafafa;
    }
    
    .pagination-info {
      color: #666;
      font-size: 14px;
    }
    
    .pagination-controls {
      display: flex;
      align-items: center;
      gap: 10px;
    }
    
    .page-btn {
      padding: 6px 12px;
      border: 1px solid #ddd;
      background-color: white;
      border-radius: 4px;
      cursor: pointer;
      font-size: 14px;
      transition: all 0.3s;
    }
    
    .page-btn:hover:not(:disabled) {
      border-color: #1E9FFF;
      color: #1E9FFF;
    }
    
    .page-btn:disabled {
      cursor: not-allowed;
      opacity: 0.5;
    }
    
    .page-jump {
      display: flex;
      align-items: center;
      gap: 10px;
    }
    
    .page-jump input {
      width: 60px;
      padding: 6px;
      border: 1px solid #ddd;
      border-radius: 4px;
      text-align: center;
    }
    
    .jump-btn {
      padding: 6px 12px;
      background-color: #1E9FFF;
      color: white;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: background-color 0.3s;
    }
    
    .jump-btn:hover {
      background-color: #40A9FF;
    }

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 500px;
  max-height: 80vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.close-btn:hover {
  color: #333;
}

.modal-body {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #666;
  font-weight: 500;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.submit-btn {
  background-color: #1E9FFF;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.submit-btn:hover {
  background-color: #40A9FF;
}

.cancel-btn {
  padding: 8px 16px;
  border: 1px solid #ddd;
  background-color: white;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.cancel-btn:hover {
  background-color: #f5f5f5;
}
</style>